package com.javaedge.concurrency;

import com.javaedge.concurrency.annoations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

/**
 * @author JavaEdge
 */
@Slf4j
@NotThreadSafe
public class countDownLatchTest {
    // 同时并发执行的线程数
    public static int threadTotal = 5;

    public static void main(String[] args) throws Exception {
        CountDownLatch latch = new CountDownLatch(threadTotal);
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 12; i++) {
                    try {
                        Thread.sleep(1000L);
                    } catch (InterruptedException e) {
                        log.error("exception", e);
                    }
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            latch.countDown();
                            Long count = latch.getCount();
                            if (count > 0) {
                                log.info("用户{}组队准备，还在等待{}人准备", Thread.currentThread().getName(), latch.getCount());
                            } else {
                                log.info("用户{}组队准备，房间已满不可加入", Thread.currentThread().getName());
                            }
                        }
                    }).start();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    log.info("游戏房间等待玩家加入....");
                    latch.await();
                    log.info("游戏房间已锁定");
                } catch (InterruptedException e) {
                    log.error("exception", e);
                }
            }
        }).start();
        log.info("游戏玩家准备中....");
        latch.await();
        log.info("游戏匹配中");
    }
}
